package suzf.top.usercenter.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.activity_user_info.*
import suzf.top.base.ext.onClick
import suzf.top.base.ui.activity.BaseMvpActivity
import suzf.top.usercenter.injection.component.DaggerUserComponent
import suzf.top.usercenter.injection.module.UserModule
import suzf.top.usercenter.presenter.UserInfoPresenter
import suzf.top.usercenter.presenter.view.UserInfoView
import com.bigkoo.alertview.AlertView
import com.bigkoo.alertview.OnItemClickListener
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.app.TakePhotoImpl
import com.jph.takephoto.compress.CompressConfig
import com.jph.takephoto.model.TResult
import suzf.top.base.utils.AppPrefsUtils
import com.kotlin.base.utils.DateUtils
import suzf.top.base.utils.GlideUtils
import com.qiniu.android.storage.UploadManager
import org.jetbrains.anko.toast
import suzf.top.base.common.BaseConstant
import suzf.top.provider.common.ProviderConstant
import suzf.top.usercenter.R
import suzf.top.usercenter.data.protocol.UserInfo
import suzf.top.usercenter.utils.UserPrefsUtils
import java.io.File


/**
 *  用户信息界面
 *========================
 * Created with AndroidStudio
 * Author:Mr.Su
 * Date:2019-09-07
 * Time:20:46
 * ========================
 */
class UserInfoActivity : BaseMvpActivity<UserInfoPresenter>(), UserInfoView, View.OnClickListener, TakePhoto.TakeResultListener {

    private lateinit var mTakePhoto: TakePhoto
    private lateinit var mTempFile: File
    private val mUploadManager: UploadManager by lazy { UploadManager() }

    private var mLocalFileUri: String? = null
    private var mRemoteFileUri: String? = null

    private var mUserIcon: String? = null
    private var mUserName: String? = null
    private var mUserMobile: String? = null
    private var mUserGender: String? = null
    private var mUserSign: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)

        mTakePhoto = TakePhotoImpl(this, this)
        mTakePhoto.onCreate(savedInstanceState)

        initView()
        initData()
    }

    /**
     * 初始化视图
     */
    private fun initView() {
        mUserIconView.onClick {
            showAlertView()
        }
        mHeaderBar.getRightView().onClick {
            mPresenter.editUser(mRemoteFileUri!!,
                    mUserNameEt.text?.toString()?:"",
                    if (mGenderMaleRb.isChecked) "0" else "1",
                    mUserSignEt.text?.toString()?:"")
        }
    }

    /**
     * 初始化数据
     */
    private fun initData() {
        mUserIcon = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_ICON)
        mUserName = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_NAME)
        mUserMobile = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_MOBILE)
        mUserGender = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_GENDER)
        mUserSign = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_SIGN)

        mRemoteFileUri = mUserIcon
        if (mUserIcon != "") {
            GlideUtils.loadUrlImage(this@UserInfoActivity, mUserIcon!!, mUserIconIv)
        }
        mUserNameEt.setText(mUserName)
        mUserMobileTv.text = mUserMobile
        if (mUserGender == "0") {
            mGenderMaleRb.isChecked = true
        } else {
            mGenderFemaleRb.isChecked = true
        }
        mUserSignEt.setText(mUserSign)
    }

    /**
     * 显示Alert
     */
    private fun showAlertView() {
        AlertView("上传头像", null, "取消", null, arrayOf("拍照", "从相册中选择"),
                this, AlertView.Style.ActionSheet, OnItemClickListener { o, position ->
            mTakePhoto.onEnableCompress(CompressConfig.ofDefaultConfig(), false)
            when (position) {
                0 -> {
                    createTempFile()
                    mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
                }
                1 -> mTakePhoto.onPickFromGallery()
            }
        }).show()
    }

    /**
     * Dagger注入
     */
    override fun injectComponent() {
        DaggerUserComponent.builder()
                .activityComponent(activityComponent)
                .userModule(UserModule())
                .build()
                .inject(this)
        mPresenter.mView = this
    }

    override fun onClick(view: View) {
        when (view.id) {

        }
    }

    /**
     * 选择成功
     */
    override fun takeSuccess(result: TResult?) {
        mLocalFileUri = result?.image?.compressPath
        mPresenter.getUploadToken()
    }

    /**
     * 取消选择
     */
    override fun takeCancel() {
    }

    /**
     * 选择失败
     */
    override fun takeFail(result: TResult?, msg: String?) {
        Log.e("Take", msg)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mTakePhoto.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 生成临时文件
     */
    private fun createTempFile() {
        val tempFileName = "${DateUtils.curTime}.png"
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            this.mTempFile = File(Environment.getDataDirectory(), tempFileName)
            return
        }
        this.mTempFile = File(filesDir, tempFileName)
    }

    /**
     * 获取上传token的回调
     */
    override fun onGetUploadTokenResult(result: String) {
        mUploadManager.put(mLocalFileUri, null, result, { key, info, response ->
            mRemoteFileUri = BaseConstant.IMAGE_SERVER_ADDRESS + response?.get("hash")
            GlideUtils.loadUrlImage(this@UserInfoActivity, mRemoteFileUri!!, mUserIconIv)
        }, null)
    }

    /**
     * 修改成功
     */
    override fun onEditUserResult(result: UserInfo) {
        toast("修改成功，刷新数据 ")
        UserPrefsUtils.putUserInfo(result)
    }

}
